package edu.hubu.web.commons

import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.ObjectMapper
import java.io.IOException
import java.io.PrintWriter
import javax.servlet.http.HttpServletResponse

/**
 * @author moonlan
 * date 2020/10/20 下午2:23
 */
class ResultsJson {
    var code: Int? = null
    var msg: String? = null
    var total: Int? = null
    var current: Int? = null
    var data: Any? = null

    constructor(){}
    constructor(code: Int?, msg: String?, total: Int?, current: Int?, data: Any?) {
        this.code = code
        this.msg = msg
        this.total = total
        this.current = current
        this.data = data
    }


    companion object {
        @JvmStatic
        fun toJson(code: StatusCode?, total: Int?, current: Int?, data: Any?): ResultsJson {
            return ResultsJson(code!!.code, code.msg, total, current, data)
        }

        @JvmStatic
        fun toJson(code: Int?, msg: String?, total: Int?, current: Int?, data: Any?): ResultsJson {
            return ResultsJson(code, msg, total, current, data)
        }

        @JvmStatic
        fun toJson(code: Int?, msg: String?, total: Int?, current: Int?, data: Any?, response: HttpServletResponse) {
            val mapper = ObjectMapper()
            val writer: PrintWriter
            writer = try {
                response.writer
            } catch (e: IOException) {
                throw RuntimeException(e)
            }
            try {
                val value = mapper.writeValueAsString(ResultsJson(code, msg, total, current, data))
                writer.write(value)
            } catch (e: JsonProcessingException) {
                throw RuntimeException(e)
            } finally {
                writer.close()
            }
        }
    }
}